<template>
  <!--日期选择-->
  <el-row :gutter="10" style="background-color: rgba(208,208,208,0.2);justify-content: center;margin-left: 40px;margin-right: 40px;">
    <el-col :span="3" v-for="date in dateList" :key="date.id">
      <el-card
          class="date-card"
          :class="{ 'is-selected': selectedDateIndex === date.id }"
          @click="selectDate(date.id,date.date)"
          shadow="hover"
      >
        <div style="display: flex;flex-direction: column;">
          <span style="font-size: 16px;">{{ date.showDate }}</span>
          <span style="font-size: 15px;">{{ date.day }}</span>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!--医生卡片-->
  <el-row :gutter="40" style="justify-content: center;margin-top: 16px" v-show="selectedDateIndex !== null">
    <el-col :span="11" style="margin-bottom: 20px" v-for="doctor in doctorList" :key="doctor.id">
      <el-card class="doctor-card" shadow="hover">
        <div class="content">
          <!--头像-->
          <div class="avatar">
            <el-avatar  shape="circle" class="large-avatar" :src="doctor.avatar"></el-avatar>
          </div>
          <!--医生介绍面板-->
          <div class="details">
            <div class="info">
              <div class="name-title">
                <span class="name">{{ doctor.name }}</span>
                <span class="title">{{ getTitle(doctor.title) }}</span>
              </div>
              <div class="expertise">{{ doctor.researchField }}</div>
            </div>
            <div class="fee">
              <span class="shift"> {{ doctor.shift === 0 ? '上午' : '下午' }}</span>
              <span class="price">￥{{ getFee(doctor.title) }}</span>
              <el-button type="primary" class="register-button" @click="choDoctor(doctor)">挂号</el-button>
            </div>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>

      <!--时间选择-->

        <el-dialog
            title="选择时间"
            v-model="timeSlotVisible"
            width="30%"
            @close="resetSelection"
        >
          <div class="time-cards">
            <el-button
                v-for="item in regSpotsList"
                :key="item"
                class="time-card"
                :class="{ 'is-selected': selectedTime === item }"
                @click="selectTime(item)"
            >
              <div>
                <span>{{ getTime(item.timeSlot) }}</span>
                <span style="margin-left: 18px;">余号：{{ item.remainSpots }}</span>
              </div>
            </el-button>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="timeCancel">取消</el-button>
              <el-button type="primary" @click="timeConfirm">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>


</template>

<script setup>
import { ref} from "vue";
import mitt from '@/utils/mitt';
import { ElButton, ElDialog } from 'element-plus';
import { useRouter } from "vue-router";
import { useMainStore } from '@/store';
import regScheApi from "@/apis/regSche";


const router = useRouter();
const emitter = mitt;
const store = useMainStore();
const patientInfo = JSON.parse(sessionStorage.getItem('userInfo'))

/**
 * 日期选择
 */
const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const dateList = ref([]);
const today = new Date();


for (let i = 0; i < 7; i++) {
  // 创建一个新的日期对象，基于今天的日期
  const date = new Date(today);
  date.setDate(today.getDate() + i); // 设置日期为今天日期加上i天

  const dateId = i + 1; // 假设id从1开始
  const dateItem = {
    id: dateId,
    showDate:`${date.getDate().toString().padStart(2, '0')}`,
    date: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`,
    day: daysOfWeek[date.getDay()]
  };
  dateList.value.push(dateItem);
}

const selectedDateIndex = ref(null); // 添加一个响应式变量来跟踪选中的卡片索引
const selectedDate = ref(null); // 添加一个响应式变量来跟踪选中的卡片索引
/**
 * 选择日期
 * @param dateIndex
 * @param date
 */
const selectDate = (dateIndex, date) => {
  selectedDate.value = date;
  getDoctorList(date);
  selectedDateIndex.value = selectedDateIndex.value === dateIndex ? null : dateIndex;
  if(selectedDateIndex.value!==null){
    emitter.emit('next', 2);
  }else{
    emitter.emit('next', 1);
  }

};




/**
 * 获取当前门诊当天挂号排班列表信息-进一步筛出有排班的医生信息 使用doctorId和shift
 * 用 todayStr, clinicId 去获取status=2的排班列表 regScheList
 */
// const regScheList = ref([])

const doctorList = ref([])

const getDoctorList = async (date) =>{
  const data = {
    date:date,
    clinicId:store.getDepartAndClinic.clinicId //获取从前面传来的clinicId
  }
  const res = await regScheApi.getRegScheListByCon(data)
  if(res.code === 200){
    doctorList.value = res.data;
  }else {
    doctorList.value = null;
  }
  // console.log(doctorList.value)
}


/**
 * 医生卡片信息绑定
 */
const titleFeeTotal = ref([
  { id: 0, name: '医师', fee: 10 },
  { id: 1, name: '主治医师', fee: 10 },
  { id: 2, name: '副主任医师', fee: 20 },
  { id: 3, name: '主任医师', fee: 30 }
]);

function getTitle(titleId){
  const one = titleFeeTotal.value.find(item => item.id === titleId);
  return one ? one.name : ''; // 如果找到对应的职称ID，返回name，否则返回空字符串
}
function getFee(titleId){
  const one = titleFeeTotal.value.find(item => item.id === titleId);
  return one ? one.fee : ''; // 如果找到对应的职称ID，返回name，否则返回空字符串
}


const timeSlotVisible = ref(false);  //时间选择
const regSpotsList = ref([])
const selectedDoctor = ref(null)
/**
 * 点击挂号
 * @param doctor
 */
const choDoctor = async (doctor) => {
  console.log(doctor)
  selectedDoctor.value = doctor;
  const data ={
    regScheId:doctor.regScheId
  }
  regSpotsList.value = (await regScheApi.getRegSpotsByCon(data)).data
  console.log(regSpotsList.value)
  timeSlotVisible.value = true

  if(timeSlotVisible.value){
    //弹窗->加进度
    emitter.emit('next', 3);
  }
}


/**
 * 时间选择
 */

const selectedTime = ref(null);

const times = ref([
  {id:0,name:'08:00-08:30'},
  {id:1,name:'08:30-09:00'},
  {id:2,name:'09:00-09:30'},
  {id:3,name:'09:30-10:00'},
  {id:4,name:'10:00-10:30'},
  {id:5,name:'10:30-11:00'},
  {id:6,name:'14:00-14:30'},
  {id:7,name:'14:30-15:00'},
  {id:8,name:'15:00-15:30'},
  {id:9,name:'15:30-16:00'},
  {id:10,name:'16:00-16:30'},
  {id:11,name:'16:30-17:00'},
]);

function selectTime(item) {
  selectedTime.value = item;
}

function resetSelection() {
  selectedTime.value = null;
}

function getTime(timeSlot){
  const one = times.value.find(item => item.id === timeSlot);
  return one ? one.name : ''; // 如果找到对应的职称ID，返回name，否则返回空字符串
}


const timeConfirm = () =>{
  /**
   * 存储挂号记录信息到store
   * 就诊日期、就诊科室、医生姓名、医生职称、患者姓名、就诊卡号、挂号费用
   */
  const registerInfo = {
    date:selectedDate.value,
    timeSlotId:selectedTime.value.timeSlot,
    timeSlot:getTime(selectedTime.value.timeSlot),
    departmentId:store.getDepartAndClinic.departmentId,
    departmentName:store.getDepartAndClinic.departmentName,
    clinicId:store.getDepartAndClinic.clinicId,
    clinicName:store.getDepartAndClinic.clinicName,
    doctorId:selectedDoctor.value.id,
    doctorName:selectedDoctor.value.name,
    doctorTitle:getTitle(selectedDoctor.value.title),
    patientId:patientInfo.id,
    patientName:patientInfo.name,
    medicalCard:patientInfo.medicalCard,
    fee:getFee(selectedDoctor.value.title),
    regSpotsId:selectedTime.value.id
  }
  // store.setRegisterInfo(registerInfo)
  sessionStorage.setItem('regInfo',JSON.stringify(registerInfo))

  timeSlotVisible.value = false
  //关闭弹窗->加进度
  emitter.emit('next', 4);
  router.push({name:'RegisterConfirm'});
}

const timeCancel = () =>{
  timeSlotVisible.value = false
  //关闭弹窗->减进度
  emitter.emit('next', 2);
}


</script>

<style scoped>
.date-card {
  margin: 10px;
  cursor: pointer; /* 让鼠标悬停时显示为手型 */
  text-align: center; /* 使卡片内的内容水平居中 */
  justify-items: center; /* 水平居中 */
  transition: background-color 0.3s; /* 平滑过渡背景色变化 */
}

.date-card.is-selected {
  //background-color:rgba(65, 159, 255, 0.20);
  border-width: 2px;
  border-color: rgba(65, 159, 255, 0.60);
}

.doctor-card{
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #ccc;
}


.content {
  display: flex;
  align-items: center; /* 使头像和文本垂直居中 */
}

.avatar {
  margin-right: 40px;
}

.large-avatar {
  width: 80px !important;
  height: 80px !important;
}

.details {
  display: flex;
  flex-direction: column; /* 姓名、职称和擅长领域垂直排列 */

}

.info {
  flex-grow: 1;
}

.name-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.name {
  font-size: 20px;
  font-weight: bold;
  margin-right: 10px;
}

.title {
  font-size: 16px;
  color: #666;
}

.expertise {
  color: #333;
}

.fee {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-top: 10px;
}

.shift{
  font-size: 16px;
  margin-right: 15px;
}

.price {
  font-size: 16px;
  color: red;
  margin-right: 15px;
}

.total {
  font-size: 15px;
  color: #3b90ee;
  margin-right: 5px;
}

.register-button {
  border-radius: 5px;
  padding: 10px 20px;
}

.time-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 250px;
  margin: 0 auto; /* 水平居中 */
}
.time-card {
  margin-left: 12px;
  flex: 1 1 200px; /* Adjust the width as needed */
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  transition: background-color 0.3s;
}
.time-card.is-selected {
  background-color: #f0f9ff;
  border-color: #409eff;
  color: #409eff;
}
</style>
